<template>
  <div class="container header ">
    <My-header title="上传拜访记录"  >
      <span class="left"  @click="godetail(cname,cid)"><i class="icon icon-back" ></i></span>
    </My-header>
    <div class="content">
      <div class="add-form">
         <!-- <div class="form-item">
          <span class="label">店铺</span>
          <input type="text" v-model="shopName" placeholder="店铺名称" >
        </div>
        
        <div class="form-item">
          <span class="label">电话</span>
          <input type="tel" v-model="tel" placeholder="电话">
        </div>  -->
         <div class="form-item">
          <span class="label">地址</span>
          <input type="text" readonly :value="address_detail" placeholder="省市区" id="allmap">
        </div>
       
        <div class="form-item">
          <span class="label">店铺照片</span>
          <div class="img_container">
            <div v-for="img of imgs" :key="img" class="img" :style="`background:url(${ossimg}${img})`"></div>
            <div v-if="imgs.length < 4" class="add_img">
              <input @change="fileChange($event)" type="file">
            </div>
          </div>
        </div> 
         <div class="form-item">
          <span class="label">备注</span>
          <input type="text" v-model="summery" placeholder="说明" >
        </div> 
       
        
        <Btn @onclick="savebfjl()" class=""  value="提交" :disable="!valid.r"></Btn>
        
      </div>
    </div>
   
  </div>
</template>

<script>
import MyHeader from "@/components/MyHeader.vue";
import Btn from "@/components/Btn.vue";
import { mapState, mapActions } from "vuex";
import axios from "axios";
import qs from 'qs';
import { isPoneAvailable } from "@/util";
export default {
  name: "uploadBf",
  data() {
    return {
      name: "",
      tel: "",
      province: "",
      city: "",
      district: "",
      address: "",
      addr: "",
      lat: "",
      lng: "",
     
      baseurl: "",
      imgs: [],
      address_detail:"",
      summery:'',
      cid:''
    };
  },
  components: {
    MyHeader,
    Btn
  },
  computed: {
    ...mapState(["addressList", "userInfo", "toUser", "ossimg" ,"fromUser"]),

    valid() {
      // if (!isPoneAvailable(this.tel)) {
      //   return { r: false, msg: "请输入正确手机号" };
      // }
      
     
      if (this.address_detail.length === 0) {
        return { r: false, msg: "请选择地址" };
      }
     
      if (this.imgs.length === 0) {
        return { r: false, msg: "请上传照片" };
      }
      if (this.summery.length === 0) {
        return { r: false, msg: "请输入说明" };
      }
      
      return { r: true, msg: "" };
    },
    // ssq() {
    //   return this.province + this.city + this.district;
    // }
  },
  mounted() {
   
    this.map();
    this.cid   = this.$route.params.id;
    this.cname = this.$route.params.name;
   
  },
  methods: {
    
    selectTab(id) {
      this.tabId = id;
    },
    godetail(name,id) {
      this.$router.push({ name: "clientDetail", params: { name,id } });
    },
     //保存拜访记录
    savebfjl() {
      if (!this.valid.r) {
        this.$toast(this.valid.msg);
        return;
      }
   
      this.$loading("加载中...");
      axios
        .get("/cust/custbf!saveajax.action", {
          params: {
            toUser: this.userInfo.toUser,
            cid: this.cid,
            sellid:this.userInfo.id,
            insdate:'',
            addr: this.address_detail,
            sm:  this.summery,
            lat: this.lat,
            lon: this.lng,
            pic: this.imgs.join() //将数组变成逗号隔开字符串
          }
        })
        .then(() => {
          this.$loading.close();
          this.$toast("添加成功");
         
          var name=this.cname;
          var id=this.cid;
          //history.back();//携带不了参数
          //上传完，跳转页面
           this.$router.push({ name: "clientDetail", params: { name,id} });
        })
        .catch(function(error) {
          window.console.log(error);
        });
    },
    
  
    // 上传照片
    fileChange(e) {
      const vm = this;
      const file = e.target.files[0];
      if(file.type.indexOf("image") !== 0) {
        this.$toast("请选择图片");
        return;
      }
      this.$loading("上传中...");
      const createObjectURL = window.webkitURL ? window.webkitURL.createObjectURL : window.URL.createObjectURL;
      convertImgToBase64(
        //window.URL.createObjectURL(file),
        createObjectURL(file),


        function(base64Img) {
          const instance = axios.create({
            headers: {
              "Content-Type": "application/x-www-form-urlencoded"
            }
          });
          instance({
            method: "post",
            url: "/wwz/wwzajax!upimage.action",
            data: qs.stringify({ baseurl: base64Img })
          })
            .then(response => {
              vm.$toast("上传成功");
              vm.$loading.close();
              if(response.data.state === 0) {
                vm.imgs.push(response.data.path)
              }
            })
            .catch(error => {
              window.console.log(error);
            });
        }
      );
      function convertImgToBase64(url, callback, outputFormat) {
        let canvas = document.createElement("CANVAS"),
          context = canvas.getContext("2d"),
          img = new Image();
        img.crossOrigin = "Anonymous";
        img.onload = function() {
          // 图片原始尺寸
          let originWidth = this.width;
          let originHeight = this.height;
          // 最大尺寸限制，可通过国设置宽高来实现图片压缩程度
          let maxWidth = 800,
              maxHeight = 800;
          // 目标尺寸
          let targetWidth = originWidth,
              targetHeight = originHeight;
          // 图片尺寸超过400x400的限制
          if(originWidth > maxWidth || originHeight > maxHeight) {
              if(originWidth / originHeight > maxWidth / maxHeight) {
                  // 更宽，按照宽度限定尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
              } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
          }
          // canvas对图片进行缩放
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
          /*第一个参数是创建的img对象；第二个参数是左上角坐标，后面两个是画布区域宽高*/
          //压缩后的图片base64 url
          /*canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是'image/jpeg';
            * qualityArgument表示导出的图片质量，只要导出为jpg和webp格式的时候此参数才有效果，默认值是0.92*/
          let newUrl = canvas.toDataURL('image/jpeg' , 0.92);//base64 格式
          callback.call(this, newUrl);
          canvas = null;
        };
        img.src = url;
      }
    },
    map() {
      var vm = this; 
      var geolocation = new BMap.Geolocation(); 
        geolocation.getCurrentPosition(function(r){ 
          if(this.getStatus() == BMAP_STATUS_SUCCESS){ 
            var myGeo = new BMap.Geocoder();
            myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), function(result){ 
              if (result){
                  vm.address_detail= result.addressComponents.province+result.addressComponents.city+ result.addressComponents.district+result.addressComponents.street
                  vm.lat = r.point.lat || 116.331398;
                  vm.lng = r.point.lng || 39.897445;
                  console.log(vm.lat+'---'+vm.lng)
              }
            });
          } 
      });
      
    }
 
  },
};
</script>

<style lang="scss">
.content {
    //  height: 120% !important; 
     overflow: auto !important;
   
}

.img_container {
  padding: 0 0.5rem;
  overflow: hidden;
  div {
    height: 5rem;
    width: 5rem;
    float: left;
    margin-right: 0.5rem;
    margin-bottom: 0.5rem;
    background-size: cover !important;
  }
  .add_img {
    border: 1px solid #ccc;
    position: relative;
    input[type="file"] {
      opacity: 0;
      display: block;
      width: 100%;
      height: 100%;
    }
    &::before {
      content: "";
      display: block;
      width: 0.2rem;
      height: 80%;
      background: #ababab;
      left: 50%;
      position: absolute;
      top: 10%;
    }
    &::after {
      content: "";
      display: block;
      width: 80%;
      height: 0.2rem;
      background: #ababab;
      left: 10%;
      position: absolute;
      top: 50%;
    }
  }
}
.add-form {
  margin: 0 1rem;
  margin-top: 1rem;
  .btns {
    margin-top: 4rem;
  }
  .form-item {
    padding-left: 4rem;
    line-height: 3rem;
    margin-bottom: 1rem;
    position: relative;
    text-align: center;
    .toggle-btn {
      position: absolute;
      right: 0.5rem;
      top: 0;
      height: 100%;
      left: auto;
      width: 2rem;
      .icon {
        font-size: 1.5rem;
      }
    }
    .label {
      position: absolute;
      width: 4rem;
      left: 0;
    }
    input {
      display: block;
      height: 100%;
      width: 100%;
      border: 0;
      outline: none;
      padding: 0 0.5rem;
      height: 3rem;
      font-size: 1rem;
      color: #666;
      border-bottom: 1px solid #ccc;
    }
    input[readonly="readonly"] {
      background: #eee;
    }
    .map {
      width: 100%;
      height: 12rem;
    }
    .note {
      line-height: 2rem;
      text-align: left;
      font-size: 0.6rem;
      color: #999;
    }
  }
  & + .btn {
    margin-top: 2rem;
  }
  .textcolor {
    color: #c0c0c0;
    padding: 0.6rem;
    margin-bottom: 0.8rem;
  }
}
.tab-header {
  &.bind {
    position: relative;
  }
  .width {
    width: 100%;
  }
}
.butt{
    clear: both;
    position: fixed;
    bottom: 0px;
    left: 0px;
    width: 100%;
    z-index: 1000;
    margin:0rem !important;
}
</style>
